#include"tcpClient.h"
#include"logger.h"
#include"msg.h"
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string.h>
#include<iostream>
#include<unistd.h>

TcpClient::TcpClient(const IpAddressPort& ipAddressAndPort)
{
    m_msfd=socket(AF_INET,SOCK_STREAM,0);
    if(-1==m_msfd)
    {
        LOG_FATAL<<strerror(errno);
    }
    struct sockaddr_in ser;
    ser.sin_family=AF_INET;
    ser.sin_port=htons(ipAddressAndPort.GetPort());
    ser.sin_addr.s_addr=inet_addr(ipAddressAndPort.GetIpAddress().c_str());
    if(-1==connect(m_msfd,(struct sockaddr*)&ser,sizeof(ser)))
    {
        LOG_FATAL<<strerror(errno);
    }
    LOG_INFO<<"connect success";
}
TcpClient::~TcpClient()
{
    if(-1==close(m_msfd))
    {
        LOG_FATAL<<strerror(errno);
    }
}
int TcpClient::SendMsg(const std::string&msg)
{
    int res=send(m_msfd,msg.c_str(),strlen(msg.c_str()),0);
    if(-1==res)
    {
        LOG_ERROR<<strerror(errno);
    }
    return res;
}
Msg TcpClient::RecvMsg()
{
    char buf[LARGE_BUF_LEN]={0};
    int numberOfRecvByte=recv(m_msfd,buf,LARGE_BUF_LEN,0);
    if(-1==numberOfRecvByte)
    {
        LOG_ERROR<<strerror(errno);
    }
    //c风格
    //return Msg{.m_msg=buf,.m_numberOfRecvBytes=numberOfRecvBytes};
    return Msg{buf,numberOfRecvByte};
}
int TcpClient::GetSfd()const
{
    return m_msfd;
}

int main()
{
    IpAddressPort ser("127.0.0.1",5000);
    TcpClient client(ser);
    while(1)
    {
        std::cout<<"请输入:"<<std::endl;;
        fflush(stdout);
        char buff[128]={0};
        fgets(buff,128,stdin);
        if(strncmp(buff,"end",3)==0)
        {
            break;
        }
        client.SendMsg(buff);
        Msg m=client.RecvMsg();
        LOG_INFO<<m.ToString();
        memset(buff,128,0);
    }
    return 0;
}